<?php
/**
 * Created by PhpStorm.
 * User: 86158
 * Date: 2021/7/10
 * Time: 0:51
 */

namespace App\Models\exams;


use App\Models\Model;
use App\Models\User;
use App\Services\exam\ExamService;
use Carbon\Carbon;

class UserExam extends Model
{
    protected $fillable = [
        'exam_id',
        'user_id',
        'start_time',
        'end_time',
        'continue_time',
        'score'
    ];

    public function exam()
    {
        return $this->hasOne(Exam::class,'id','exam_id');
    }

    public function user()
    {
        return $this->hasOne(User::class,'id','user_id');
    }

    public function add($data)
    {
        return self::create($data);
    }

    public static function checkStatus()
    {
        $data = self::with('exam')->whereNull('end_time')->get();
        foreach ($data as $item){
            if(Carbon::parse(Carbon::now())->diffInMinutes($item['start_time']) >= $item['exam']['minute']) {
                $item->end_time = Carbon::now();
                $item->continue_time = $item['exam']['minute'];
                $item->score = ExamService::calculate($item['id']);
                $item->save();

            }
        }
    }
}